# -*- coding:utf-8 -*-
# @Time : 3/10/21 4:43 PM
# @Author :  rebeater
# @File : NavParser.py
# @Project:  NavigationTool_qt
# @Function: Nav文件读写转换

import numpy as np
import pandas as pd
import simplekml


class NavParser:
    def __init__(self):
        self.data = None

    def to_csv(self, csv_path: str, fmt: str, header: str):
        pass

    def to_nav(self, nav_path: str, header: bool = False):
        with open(nav_path, 'w') as f:
            for d in self.data:
                f.write("%5d %.4f %.12f %.12f %.4f %.5f %.5f %.5f %.5f %.5f %.5f\n" %
                        (d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], d[8], d[9], d[10])
                        )

    def to_kml(self, kml_path: str, point_color: str = "FFFF0000", track_color: str = "FFFF0000", down_sample=1):
        colors = {'blue': 'FFFF0000', 'red': "FF0000FF", 'green': 'FF00FF00', 'yellow': 'FF00FFFF', 'pink': 'FFFFFF00',
                  'orange': "FF00A5FF"
                  }
        if track_color in colors:
            trk_color_str = colors[track_color]
        else:
            trk_color_str = track_color
        if point_color in colors:
            pnt_color_str = colors[point_color]
        else:
            pnt_color_str = point_color
        kml = simplekml.Kml()
        pnints = kml.newfolder(name="Points")
        pnt_style = simplekml.Style()
        pnt_style.iconstyle.color = pnt_color_str
        pnt_style.iconstyle.scale = 0.8
        pnt_style.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png'
        line_coords = []
        cnt = 0
        for d in self.data:
            if cnt % down_sample == 0:
                line_coords.append((d[3], d[2]))
                pnt = pnints.newpoint(
                    coords=[(d[3], d[2], d[4])])
                pnt.style = pnt_style
                pnt.description = "Epoch:%.3f\nLat=%.8f,lon=%.8f,h=%.3f" % (
                    d[1], d[2], d[3], d[4])
            cnt += 1
        lines = kml.newlinestring(name="track", description="", coords=line_coords)
        lines.style.linestyle.width = 1
        lines.style.linestyle.color = trk_color_str
        kml.save(kml_path)

    def from_array(self, data):
        col = data.shape[1]
        if col > 10:
            self.data = data
        else:
            self.data = np.zeros([data.shape[0], 11], np.double)
            self.data[:, :col] = data

    def from_nav(self, nav_path: str):
        data = np.genfromtxt(nav_path)
        self.from_array(data)

    def from_csv(self, csv_path: str):
        data = pd.read_csv(csv_path)
        self.from_array(data.values)


if __name__ == '__main__':
    parse = NavParser()
    parse.from_nav("/media/rebeater/hd_data2/workspace/share/论文用到的数据/实验结果/不同设备/sc2MTmxt906b_pred_z.csv.nav")

    parse.to_nav("/media/rebeater/hd_data2/workspace/share/论文用到的数据/实验结果/不同设备/sc2taidou_pred_z.csv.nav")
